package com.wuqing.consumer.task;

import com.wuqing.bean.MethodInvokeRecord;
import com.wuqing.utils.TpMonitorHelper;
import org.apache.commons.collections4.MapUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author wuqing
 * @date 2020/8/8
 */
@Component
public class TpMonitorTask implements InitializingBean {

    private final ScheduledExecutorService task90 = Executors.newSingleThreadScheduledExecutor(
            new NamedThreadFactory("schedule-task90"));

    private final ScheduledExecutorService task99 = Executors.newSingleThreadScheduledExecutor(
            new NamedThreadFactory("schedule-task99"));

    @Override
    public void afterPropertiesSet() {
        task90.scheduleAtFixedRate(() -> monitor(0.90), 7, 5, TimeUnit.SECONDS);
        Runtime.getRuntime().addShutdownHook(new Thread(task90::shutdown));

        task99.scheduleAtFixedRate(() -> monitor(0.99), 10, 5, TimeUnit.SECONDS);
        Runtime.getRuntime().addShutdownHook(new Thread(task99::shutdown));
    }

    private void monitor(double percent) {
        double param = percent * 100;
        Map<String, MethodInvokeRecord> ptResult = TpMonitorHelper.getPt(percent);
        if (MapUtils.isEmpty(ptResult)) {
            System.out.println(param + "统计结果播报:接口无人调用");
            return;
        }

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, MethodInvokeRecord> entry : ptResult.entrySet()) {
            MethodInvokeRecord record = entry.getValue();
            String format = String.format("方法名字methodName=%s，耗时=%s ms", record.getMethodName(), record.getCost());
            builder.append(format);
            builder.append(";");
        }

        String formatResult = String.format("%s统计结果ptResult播报：%s", param,builder.toString() );
        System.out.println(formatResult);
        System.out.println();
    }

}